const express = require('express');
const path = require('path');
const os = require('os');
const QRCode = require('qrcode');

class HttpServer {
  constructor(port = 7663) {
    this.port = port;
    this.app = express();
    this.server = null;
    this.setupRoutes();
  }

  setupRoutes() {
    // 提供静态文件
    const clientPath = path.join(__dirname, '../../client');
    this.app.use(express.static(clientPath));

    // 健康检查
    this.app.get('/health', (req, res) => {
      res.json({ status: 'ok', timestamp: Date.now() });
    });

    // 获取服务器信息
    this.app.get('/api/info', (req, res) => {
      const localIp = this.getLocalIpAddress();
      res.json({
        ip: localIp,
        port: this.port,
        wsUrl: `ws://${localIp}:${this.port}`
      });
    });
  }

  async start() {
    return new Promise((resolve, reject) => {
      try {
        this.server = this.app.listen(this.port, () => {
          const localIp = this.getLocalIpAddress();
          const url = `http://${localIp}:${this.port}`;
          
          console.log('\n========================================');
          console.log('PPT远程控制服务器已启动');
          console.log('========================================');
          console.log(`主要IP地址: ${localIp}`);
          console.log(`HTTP端口: ${this.port}`);
          console.log(`访问地址: ${url}`);
          console.log('========================================');
          
          // 显示所有可用的网络接口
          this.displayAllNetworkInterfaces();
          
          console.log('========================================\n');

          // 生成二维码
          this.generateQRCode(url);

          resolve();
        });

        this.server.on('error', (error) => {
          if (error.code === 'EADDRINUSE') {
            console.error(`端口 ${this.port} 已被占用`);
            reject(error);
          } else {
            console.error('HTTP服务器错误:', error);
            reject(error);
          }
        });

      } catch (error) {
        reject(error);
      }
    });
  }

  // 获取本地IP地址
  getLocalIpAddress() {
    const interfaces = os.networkInterfaces();
    const addresses = [];
    
    for (const name of Object.keys(interfaces)) {
      for (const iface of interfaces[name]) {
        // 跳过内部和非IPv4地址
        if (iface.family === 'IPv4' && !iface.internal) {
          addresses.push({
            name: name,
            address: iface.address,
            // ZeroTier网络识别：名称包含zerotier或zt，且IP在172.29段
            isZeroTier: (name.toLowerCase().includes('zerotier') || 
                        name.toLowerCase().includes('zt')) &&
                       iface.address.startsWith('172.29.'),
            // 常规局域网地址
            isLocalNetwork: iface.address.startsWith('192.168.') || 
                           iface.address.startsWith('10.'),
            // Hyper-V虚拟网络
            isHyperV: name.toLowerCase().includes('vethernet') ||
                     name.toLowerCase().includes('hyper-v')
          });
        }
      }
    }
    
    // 优先选择ZeroTier地址
    const zeroTierAddr = addresses.find(addr => addr.isZeroTier);
    if (zeroTierAddr) {
      console.log(`✓ 检测到ZeroTier网络: ${zeroTierAddr.name}`);
      return zeroTierAddr.address;
    }
    
    // 其次选择局域网地址（排除Hyper-V）
    const localAddr = addresses.find(addr => addr.isLocalNetwork && !addr.isHyperV);
    if (localAddr) {
      console.log(`✓ 使用局域网地址: ${localAddr.name}`);
      return localAddr.address;
    }
    
    // 最后返回第一个非Hyper-V地址
    const nonHyperVAddr = addresses.find(addr => !addr.isHyperV);
    if (nonHyperVAddr) {
      return nonHyperVAddr.address;
    }
    
    // 实在没有就返回第一个
    if (addresses.length > 0) {
      return addresses[0].address;
    }
    
    return 'localhost';
  }

  // 显示所有网络接口
  displayAllNetworkInterfaces() {
    const interfaces = os.networkInterfaces();
    const addresses = [];
    
    for (const name of Object.keys(interfaces)) {
      for (const iface of interfaces[name]) {
        if (iface.family === 'IPv4' && !iface.internal) {
          addresses.push({
            name: name,
            address: iface.address
          });
        }
      }
    }
    
    if (addresses.length > 1) {
      console.log('\n其他可用的网络地址:');
      addresses.forEach(addr => {
        const url = `http://${addr.address}:${this.port}`;
        console.log(`  - ${addr.name}: ${url}`);
      });
    }
  }

  // 生成二维码
  async generateQRCode(url) {
    try {
      const qrText = await QRCode.toString(url, {
        type: 'terminal',
        small: true
      });
      console.log('扫描二维码快速连接:');
      console.log(qrText);
    } catch (error) {
      console.error('生成二维码失败:', error);
    }
  }

  // 停止服务器
  stop() {
    if (this.server) {
      this.server.close(() => {
        console.log('HTTP服务器已关闭');
      });
    }
  }
}

module.exports = HttpServer;
